<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="./js/echarts.min.js"></script>
    <title>图表</title>
    <style>
        #container{
            display: flex;
            justify-content: center; /* 水平居中 */
            align-items: center; /* 垂直居中 */
            height: 100vh; /* 容器高度为视窗的100% */
        }
    </style>
</head>
<body>
    <div id="container">
        <div id="main" style="width: 600px;height:400px;"></div>
    </div>
    

    <script>
      // 基于准备好的dom，初始化echarts实例
      var myChart = echarts.init(document.getElementById('main'));

      let data = [5, 20, 36, 10, 10, 20]
      console.log(typeof(data))
      console.log(data)

      // WebSocket 连接
        let socket;

        // 连接 WebSocket 服务器
        function connect() {
            // 连接地址
            const wsUrl = "ws://localhost:7200/data-push";

            socket = new WebSocket(wsUrl);
            // 连接成功
            socket.onopen = function(e) {
                console.log('连接成功')
            };

            // 收到消息
            socket.onmessage = function(event) {
                const message = event.data;
                data = JSON.parse(message)
                console.log(data)
                console.log(typeof(data))
                //如果是vue应该直接改数据值就行
                myChart.setOption({
                    series: {
                        data: data
                    }
                });
            };

            // 连接关闭
            socket.onclose = function(event) {
                if (event.wasClean) {
                    console.log(event)
                    console.log(event.reason)
                } else {
                    // 尝试重新连接
                    setTimeout(connect, 5000);
                }
            };
            // 异常
            socket.onerror = function(error) {
                console.log(error.message)
            };
        }
        //连接websocket
        connect()

      // 指定图表的配置项和数据
      var option = {
        title: {
          text: 'ECharts 入门示例'
        },
        tooltip: {},
        legend: {
          data: ['销量']
        },
        xAxis: {
          data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
        },
        yAxis: {},
        series: [
          {
            name: '销量',
            type: 'bar',
            data: data
          }
        ]
      };

      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);
    </script>
</body>
</html>